<?php

namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Comm\CommonController as common;
use App\Http\model\Dictionary;


class User extends Model
{
	/**
	 * [loginModel 登录模型]
	 * @Author   孙丽男
	 * @DateTime 2018-06-04
	 * @param    [用户信息]  array  $userInfo
	 * @version  6.2
	 * @return   [json]    [$result]
	 */
	public function loginModel($where){

		$result = array();

		$fields = array(
				'id',
				'name',
				'number',
				'phone',
			);
		$user = Db::table('user')
					->where($where)
					->select($fields)
					->first();

		if ($user) {
			$date = date('Y-m-d H:i:s');
			$update['last_time'] = $date;
			$up = Db::table('user')
					->where($where)
					->update($update);
			$userArr = json_decode(json_encode($user),true);
			session(['uid'=> $userArr['id']]) ;
			session(['username'=> $userArr['name']]);
			session(['number'=> $userArr['number']]);
			$result['code'] = 1000;
    		$result['msg'] = '登陆成功';  		

		}else{

			$result['code'] = 1004;
    		$result['msg'] = '登录失败';
		}

		return json_encode($result);

	}

	/**
	 * [showDepartModel 部门名称显示model]
	 * @Author   孙丽男
	 * @DateTime 2018-06-04
	 * @version  6.2
	 * @return   [json]    [$result]
	 */
	public function departListModel(){
		$fields = array(
				'id',
				'fullname as value',
				'pid'
			);
		$departObj = Db::table('department')
						->select($fields)
						->orderBy('sort')
						->get();
		$departArr = json_decode(json_encode($departObj),true);

		if ($departArr) {
			$comm = new Common;
			//处理数组
			$data = $comm->createTree($departArr);
			$result['code'] = 1000;
    		$result['msg'] = '查询成功';
    		$result['data'] = $data;
    		return $result;
		}else{

			$result['code'] = 1004;
    		$result['msg'] = '查询部门失败';
    		return $result;
		}

		return json_encode($result);
		
	}
	/**
	 * [addUser 添加用户模型]
	 * @Author   孙丽男
	 * @DateTime 2018-06-04
	 * @param    [用户信息]  array  $userInfo
	 * @version  6.2
	 * @return   [json]    [$result]
	 */
	public function addUserModel($userInfo = ''){
	
		$result = array();
		//角色id
		$roleId = $userInfo['role_id'];
		
		$userInfo['password'] = "###" . md5(md5('123456'));
		$userInfo['ip'] = $_SERVER["REMOTE_ADDR"];;
		$userInfo['update_time'] = date('Y-m-d H:i:s');
		$userInfo['update_user'] = session('username');

		//添加用户表信息时，删除角色id
		unset($userInfo['role_id']);

		$userArr = Db::table('user')
						->where('number',$userInfo['number'])
						->orwhere('phone',$userInfo['phone'])
						->select('id')
						->first();

		if ($userArr) {
			
			$result['code'] = 1005;
    		$result['msg'] = '用户已存在';
    		return $result;
		}

		//开启事务，用户表数据与用户角色衍生表都添加成功，提交事务，不成功回滚
		DB::beginTransaction();

		$userId = Db::table('user')->insertGetId($userInfo);
	
		if ($userId) {
					//构建添加用户角色验证表信息

				$userRole['user_id'] = $userId;
				$userRole['role_id'] = $roleId;
	

			$ur = Db::table('user_role')->insert($userRole);
			
			if ($ur) {
				
				DB::commit();
				$result['code'] = 1000;
    			$result['msg'] = '添加成功';

			}else{
				DB::rollBack();
				$result['code'] = 1004;
    			$result['msg'] = '添加失败';
			}

			
		}else{

			$result['code'] = 1004;
    		$result['msg'] = '添加失败';
    		
		}

		return json_encode($result);

	}

	/**
	 * [findUserModel 用户列表model]
	 * @Author   孙丽男
	 * @DateTime 2018-06-04
	 * @param    [查询条件]  array  $where
	 * @version  6.2
	 * @return   [json]     [$result]
	 */
	public function findUserModel($where){

		$result = array();

		$fields = array(
			'user.id',
			'user.number',
			'user.name',
			'user.sex',
			'user.email',
			'user.phone',
			'user.status',
			'user.last_time',
			'user.update_user',
			'user.update_time',
			'abbreviation',
			'roles.name as role_name',
			'roles.pid'
			);

		//根据衍生表查询用户基本信息与角色信息
		$userObj = Db::table('user_role')
						->where($where)
						->rightJoin('user','user.id','=','user_role.user_id')
						->leftJoin('department','user.department','=','department.id')
						->leftJoin('roles','roles.id','=','user_role.role_id')
						->select($fields)
						->orderBy('user.update_time', 'desc')
						->get();
		$userArr = json_decode(json_encode($userObj),true);

		if ($userArr) {
			//去重
			$userInfo = array();
			$i = 0;
			foreach ($userArr as $key => $value) {
				
				$zidian = new Dictionary;
            	$userInfo[$value['number']]['sex'] = $zidian->dictionary($value['sex']);
            	$userInfo[$value['number']]['id'] = $value['id'];
				$userInfo[$value['number']]['number'] = $value['number'];
				$userInfo[$value['number']]['name'] = $value['name'];
				$userInfo[$value['number']]['phone'] = $value['phone'];
				$userInfo[$value['number']]['email'] = $value['email'];
				if ($value['status'] == 1) {
					$userInfo[$value['number']]['status'] = '启用';
				}else{
					$userInfo[$value['number']]['status'] = '冻结';
				}
				$userInfo[$value['number']]['last_time'] = $value['last_time'];
				$userInfo[$value['number']]['update_user'] = $value['update_user'];
				$userInfo[$value['number']]['update_time'] = $value['update_time'];
				$userInfo[$value['number']]['abbreviation'] = $value['abbreviation'];
				$userInfo[$value['number']]['role'][$i]['role_name'] = $value['role_name'];
				$userInfo[$value['number']]['role'][$i]['pid'] = $value['pid'];
				$i++;

			}
			//整理数组
			$userInfoNew = array();
			//计数器
			$i = 0;
			foreach ($userInfo as $key => $value) {
				$role = '';
				foreach ($value['role'] as $ke => $val) {
					$role .= $val['role_name'].'/';
				}
				$value['role'] = $role;
				$userInfoNew[$i] = $value;
				$i++;
			}
			// print_r($userInfoNew);die;
			$result['code'] = 1000;
    		$result['msg'] = '查询成功';
    		$result['data'] = $userInfoNew;

		}else{
			$result['code'] = 1004;
    		$result['msg'] = '用户不存在';
		}
		return json_encode($result);
	}
	/**
	 * [deleteUserModel 删除用户model]
	 * @Author   孙丽男
	 * @DateTime 2018-06-04
	 * @param    [用户id数组] array $userIdArr
	 * @version  6.2
	 * @return   [json]     [$result]
	 */
	public function deleteUserModel($userIdArr){

		$comm = new Common;

		$admin = $comm->isAdmin($userIdArr,0);

		if ($admin) {

			$result['code'] = 1007;
	    	$result['msg'] = '不能删除超级管理员';
			return json_encode($result);

		}

		//开启
		DB::beginTransaction();	

		//删除用户
		$deleteUser = Db::table('user')
						->whereIn('id', $userIdArr)
						->delete();
		if ($deleteUser) {
			//删除用户角色
			$deleteUserRole = Db::table('user_role')
							->whereIn('user_id', $userIdArr)
							->delete();	
			if ($deleteUserRole) {

				DB::commit();
				$result['code'] = 1000;
    			$result['msg'] = '删除成功';

			}else{
				DB::rollBack();
				$result['code'] = 1004;
    			$result['msg'] = '删除失败';
			}

		}else{

			$result['code'] = 1004;
	    	$result['msg'] = '删除失败';
		}
		
		return json_encode($result);
	}

	/**
	 * [updateUserModel 修改用户model]
	 * @Author   孙丽男
	 * @DateTime 2018-06-04
	 * @param    [用户id] int $userId
	 * @param    [需要修改的信息] array $updateInfo
	 * @version  6.2
	 * @return   [json]     [$result]
	 */
	public function updateUserModel($userId, $updateInfo){
		$userIdArr[0] = $userId;
		$userArr = Db::table('user')
						->where([['number',$updateInfo['number']],['id','<>',$userId]])
						->orwhere([['phone',$updateInfo['phone']],['id','<>',$userId]])
						->select('id')
						->first();

		if ($userArr) {
			
			$result['code'] = 1005;
	    	$result['msg'] = '用户已经存在';
			return json_encode($result);
		}

		$comm = new Common;

		$admin = $comm->isAdmin($userIdArr,0);

		if ($admin) {

			$result['code'] = 1007;
	    	$result['msg'] = '不能修改超级管理员';
			return json_encode($result);

		}
		$updateInfo['update_time'] = date('Y-m-d H:i:s');
		$updateInfo['update_user'] = session('username');
		$updateUser = Db::table('user')
						->where('id', $userId)
						->update($updateInfo);
		if ($updateUser) {

			$result['code'] = 1000;
			$result['msg'] = '修改成功';

		}else{

			$result['code'] = 1004;
	    	$result['msg'] = '修改失败';
		}
		
		return json_encode($result);
	}

	/**
	 * [updateStatusModel 修改用户状态model]
	 * @Author   孙丽男
	 * @DateTime 2018-06-04
	 * @param    [用户id组] array $userIdArr
	 * @param    [状态] int $status
	 * @version  6.2
	 * @return   [json]     [$result]
	 */
	public function updateStatusModel($userIdArr, $status){

		$comm = new Common;

		$admin = $comm->isAdmin($userIdArr,0);

		if ($admin) {

			$result['code'] = 1007;
	    	$result['msg'] = '不能修改超级管理员状态';
			return json_encode($result);

		}

		$update['status'] = $status;
		$update['update_time'] = date('Y-m-d H:i:s');
		$update['update_user'] = session('username');
		foreach ($userIdArr as $key => $value) {
			$updateStatus[] = Db::table('user')
						->where('id', $value)
						->update($update);
		}
		
		if ($updateStatus) {

			$result['code'] = 1000;
			$result['msg'] = '修改成功';

		}else{

			$result['code'] = 1004;
	    	$result['msg'] = '修改失败';
		}
		
		return json_encode($result);

	}
	/**
	 * [rolesListModel 角色树状列表]
	 * @Author   孙丽男
	 * @DateTime 2018-06-05
	 * @version  6.2
	 * @return   [json]     [$result]
	 */
	public function rolesListModel(){

		$rolesObj = Db::table('roles')
						->select(['id','name as value','pid'])
						->get();
		$rolesArr = json_decode(json_encode($rolesObj),true);

		if ($rolesArr) {
			
			$comm = new Common;
			//处理数组
			$data = $comm->createTree($rolesArr);
			$result['code'] = 1000;
    		$result['msg'] = '查询成功';
    		$result['data'] = $data;
    		return $result;
		}else{

			$result['code'] = 1004;
    		$result['msg'] = '查询角色失败';
    		return $result;
		}

		return json_encode($result);
	}
	/**
	 * [setRolesModel 为用户设置角色]
	 * @Author   孙丽男
	 * @DateTime 2018-06-05
	 * @param    [用户id数组] array $userIdArr
	 * @param    [角色id数组] array $roleIdArr
	 * @version  6.2
	 * @return   [json]     [$result]
	 */
	public function setRolesModel($userIdArr , $roleIdArr){

		$comm = new Common;

		$admin = $comm->isAdmin($userIdArr,0);

		if ($admin) {

			$result['code'] = 1007;
	    	$result['msg'] = '不能修改超级管理员角色';
			return json_encode($result);

		}

		$result = array();

		//1、清空用户的角色 2、添加角色
		$delete = Db::table('user_role')
					->whereIn('user_id', $userIdArr)
					->delete();
		//构建添加的数据 
		$i = 0;		//计数器
		foreach ($userIdArr as $key => $value) {
			
			foreach ($roleIdArr as $k => $v) {
				
				$date[$i]['user_id'] = $value;
				$date[$i]['role_id'] = $v;
				$i++;
			}

		}

		$add = Db::table('user_role')
				->insert($date);

		if ($add) {
			
			$result['code'] = 1000;
	        $result['msg'] = '分配角色成功';
	        return json_encode($result);

		}else{

			$result['code'] = 1004;
	        $result['msg'] = '分配角色失败';
	        return json_encode($result);
		}

	}
	 /**
     * [updatePass 修改密码model]
     * @Author   孙丽男
     * @DateTime 2018-06-05
     * @param    [用户id] int $userId
     * @param    [用户密码] int $password
     * @version  6.2
     * @return   [json]     [$result]
     */
    public function updatePassModel($password){
    	$data['password'] = "###" . md5(md5($password));
    	$data['update_time'] = date('Y-m-d H:i:s');
		$data['update_user'] = session('username');
    	$uid = session('uid');
       	$res = Db::table('user')
       		->where('id',$uid)
       		->update($data);
       	if ($res) {
			
			$result['code'] = 1000;
	        $result['msg'] = '修改成功';
	        return json_encode($result);

		}else{

			$result['code'] = 1004;
	        $result['msg'] = '两次密码相同';
	        return json_encode($result);
		}
    }

    /**
     * [addDepartModel 添加部门]
     * @Author   孙丽男
     * @DateTime 2018-06-13
     * @param    [type]
     * @version  6.2
     */
    public function addDepartModel($data){
    	$data['update_user'] = session('username');
    	$data['update_time'] = date('Y-m-d H:i:s');
    	$departSort = Db::table('department')
					->where(['pid'=>$data['pid'], 'sort'=> $data['sort']])
					->first();
		if ($departSort) {

			$result['code'] = 1005;
			$result['msg'] = '父级下已存在该排序';
			return json_encode($result);

		}

		$depart = Db::table('department')
					->insert($data);
		if ($depart) {
				
			$result['code'] = 1000;
			$result['msg'] = '添加成功';

		}else{

			$result['code'] = 1004;
			$result['msg'] = '添加失败';
		}

		return json_encode($result);	
    }

    /**
     * [findDepartModel 部门列表]
     * @Author   孙丽男
     * @DateTime 2018-06-13
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
    public function findDepartModel($where){
    	$result = array();
		$departObj = Db::table('department')
						->where($where)
						->orderBy('update_time', 'desc')
						->get();
		$departArr = json_decode(json_encode($departObj),true);

		if ($departArr) {

			//整理数组
			foreach ($departArr as $key => $value) {
				
				if ($value['pid'] != 0) {

					$pname = Db::table('department')
					->where('id',$departArr[$key]['pid'])
					->select('fullname')
					->first();

					$pnameArr = json_decode(json_encode($pname), true);

					$departArr[$key]['pname'] = $pnameArr['fullname'];
					
				}else{

					$departArr[$key]['pname'] = '';
				}
			}
			$result['code'] = 1000;
			$result['msg'] = '查询成功';
			$result['data'] = $departArr;		

		}else{
			$result['code'] = 1004;
    		$result['msg'] = '没有数据';
		}
		return json_encode($result);
    }

    /**
     * [deleteDepartModel 删除部门]
     * @Author   孙丽男
     * @DateTime 2018-06-13
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
    public function deleteDepartModel($departIdArr){
    	//开启
		DB::beginTransaction();	

		//删除部门
		$deleteDepart = Db::table('department')
						->whereIn('id', $departIdArr)
						->delete();
		if ($deleteDepart) {

			//删除后该部门下用户回到顶级，递归查询顶级id
			$findUser = Db::table('user')
							->whereIn('department', $departIdArr)
							->first();
			if ($findUser) {
				$update['department'] = '';
				$updateUser = Db::table('user')
								->whereIn('department', $departIdArr)
								->update($update);	
				if ($updateUser) {

					DB::commit();
					$result['code'] = 1000;
	    			$result['msg'] = '删除成功';

				}else{
					DB::rollBack();
					$result['code'] = 1004;
	    			$result['msg'] = '删除失败';
				}

			}else{
				$result['code'] = 1000;
	    		$result['msg'] = '删除成功';
			}
			

		}else{

			$result['code'] = 1004;
	    	$result['msg'] = '删除失败';
		}
		
		return json_encode($result);
    }

    /**
     * [updateDepart 修改部门]
     * @Author   孙丽男
     * @DateTime 2018-06-13
     * @param    [type]
     * @version  6.2
     * @return   [type]     [description]
     */
    public function updateDepartModel($departId,$data){
    	$data['update_user'] = session('username');
    	$data['update_time'] = date('Y-m-d H:i:s');
    	$departSort = Db::table('department')
					->where(['pid'=>$data['pid'], 'sort'=> $data['sort']])
					->first();
		if ($departSort) {

			$result['code'] = 1005;
			$result['msg'] = '父级下已存在该排序';
			return json_encode($result);

		}

		$updateUepart = Db::table('department')
					->where('id',$departId)
					->update($data);
		if ($updateUepart) {
				
			$result['code'] = 1000;
			$result['msg'] = '修改成功';

		}else{

			$result['code'] = 1004;
			$result['msg'] = '修改失败';
		}

		return json_encode($result);	
    }
}	